﻿using System.IO;
using System.Net.Sockets;
using System.Threading;

namespace Unity
{
   
    public class Tcpclientc
    {
        private static Tcpclientc instance;
        private static object _lock = new object();
        public static Tcpclientc GetInstance()
        {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new Tcpclientc();
                    }
                }
            }
            return instance;
        }

        TcpClient client;
        byte[] data = new byte[1024];
        BinaryWriter bw;
        NetworkStream ns;
        Thread thread;
        public delegate void StateEventHandle(byte[] str);
        public event StateEventHandle CallBackStateEvent;
        public delegate void ErrorEventHandle(string str);
        public event ErrorEventHandle CallBackErrorEvent;
        public void Connect(string Ip, int port)
        {
            try
            {
                client = new TcpClient();
                client.Connect(Ip,port);
                if (client.Connected) //连接成功
                {

                }
                else
                {
                    int count = 0;
                    while (true)
                    {
                        client.Connect(Ip, port);
                        if (client.Connected)
                        {
                            count++;
                            if (count == 10)
                            {
                                Thread.Sleep(1000);
                                break;
                            }
                        }
                    }
                }
            }
            catch (SocketException)
            {
                CallBackErrorEvent?.Invoke("Unable to connect to server");
                return;
            }
            ns = client.GetStream();
            int recv=0;
            thread = new Thread(() => {
                while (true)
                {
                    data = new byte[1024];
                    recv = ns.Read(data, 0, data.Length);
                    CallBackStateEvent?.Invoke(data);
                }
            });
            thread.Start();
        }

        public void Close()
        {
            ns.Close();
            client.Close();
            thread.Abort();
            thread = null;
        }

        public void SendData(byte[] data)
        {
            NetworkStream clientStream = client.GetStream();
            bw = new BinaryWriter(clientStream);
            bw.Write(data,0, data.Length);
        }
    }
}
